package HashTable._676_ImplementMagicDictionary;

import java.util.*;

public class MagicDictionary {
    /**
     * Initialize your data structure here.
     */
    public Set<String> words;
    public Map<String, Integer> counts;
    public MagicDictionary() {
        this.words = new HashSet<>();
        this.counts = new HashMap<>();
    }

    /** Build a dictionary through a list of words */
    public void buildDict(String[] dict) {
        for (String d : dict) {
            this.words.add(d);
            for (String w : getTypes(d)) {
                this.counts.put(w, counts.getOrDefault(w, 0) + 1);
            }
        }
    }

    /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
    public boolean search(String word) {
        for (String w : getTypes(word)) {
            int count = counts.getOrDefault(w,0);
            if (count>1 ||count==1 &&!words.contains(word)) {
                return true;
            }
        }
        return false;
    }

    public List<String> getTypes(String word) {
        List<String> types = new ArrayList<>();
        char[] cha = word.toCharArray();
        for (int i = 0; i < word.length(); i++) {
            char c = cha[i];
            cha[i] = '*';
            types.add(new String(cha));
            cha[i] = c;
        }
        return types;
    }
}
